function [xMax fMax] = maxEdges(x, f, threshold)
%MAXEDGES cutting maximums of continious function f on interval x sizes of x and f MUST AGREE!
% INPUT:
%      x - arguments array;
%      f - array of values of function f(x) that corresponds to arguments
%      threshold - threshold of maximum areas
% OUTPUT:
%      xMax - row-vector of maximums arguments of multimodal function
%      fMax - row-vector of maximums values of multimodal function
%

% thresholding function in order to threshold
fThresholded = threshold * ones(1, length(f));
for i = 1:length(f)
    if (f(i) > threshold)
        fThresholded(i) = f(i);
    end;
end;

% getting number of maximum areas
inArea = false;
areasNumber = 0;
for i = 1:length(fThresholded)
    if (~inArea) && (fThresholded(i) > threshold)
        inArea = true;
        areasNumber = areasNumber + 1;
    end;
    if (inArea) && (fThresholded(i) == threshold)
        inArea = false;
    end;
end;

xMax = zeros(1, areasNumber);
fMax = zeros(1, areasNumber);

% initializing variables for loop
inArea = false;
currentAreaIndex = 0;
currentMax = threshold;
currentMaxIndex = 0;
%getting local maximums in each area
for i = 1:length(fThresholded)
    if (~inArea) && (fThresholded(i) > threshold)
        % we've entered to new area
        inArea = true;
        currentAreaIndex = currentAreaIndex + 1;
        currentMax = fThresholded(i);
        currentMaxIndex = i;
    end;
    if (inArea) && (fThresholded(i) > currentMax)
        % we are in local area and searching for maximum
        currentMax = fThresholded(i);
        currentMaxIndex = i;
    end;
    if (inArea) && ((fThresholded(i) == threshold) || (i == length(fThresholded)))
        % storing maximums
        xMax(currentAreaIndex) = x(currentMaxIndex);
        fMax(currentAreaIndex) = currentMax;
        % exit area
        inArea = false;
    end;
end;
end